package com.xxl.job.admin.dao.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.ibm.risk.common.dao.JpaDAO;
import com.ibm.risk.common.vo.PagedQueryParam;
import com.ibm.risk.common.vo.PagedQueryResult;
import com.xxl.job.admin.core.model.JobLog;
import com.xxl.job.admin.dao.IJobLogDao;

/**
 * job log
 * @author xuxueli 2016-1-12 18:03:06
 */
@Repository
@Transactional(readOnly = true)
public class JobLogDaoImpl implements IJobLogDao {
	
	@Inject
	JpaDAO dao;

	@Override
	public PagedQueryResult<JobLog> pageList(int offset, int pagesize, Long jobGroup, Long jobId, Date triggerTimeStart,
		Date triggerTimeEnd) {
		CriteriaBuilder cb = dao.getCriteriaBuilder();
		CriteriaQuery<JobLog> ctQuery = cb.createQuery(JobLog.class);
		Root<JobLog> root = ctQuery.from(JobLog.class);
		// userRoot.alias("u");
		List<Predicate> criteList = new ArrayList<Predicate>();
		if (triggerTimeStart != null) {
			criteList.add(cb.greaterThanOrEqualTo(root.<Date> get("triggerTime"), triggerTimeStart));
		}
		if (triggerTimeEnd != null) {
			criteList.add(cb.lessThan(root.<Date> get("triggerTime"), triggerTimeEnd));
		}
		if (jobId > 0) {
			criteList.add(cb.equal(root.<Long> get("jobId"), jobId));
		}
		if (jobGroup > 0) {
			criteList.add(cb.equal(root.<Long> get("jobGroup"), jobGroup));
		}
		Predicate[] predicates = criteList.toArray(new Predicate[criteList.size()]);

		ctQuery.where(predicates).orderBy(cb.desc(root.<Date> get("triggerTime")));

		PagedQueryParam queryParam = new PagedQueryParam() {
		};
		queryParam.setPageSize(pagesize);
		queryParam.setPageNumber(offset);
		PagedQueryResult<JobLog> result = dao.executePagedQuery(JobLog.class, queryParam, ctQuery, predicates);
		return result;
	}


	@Override
	public JobLog load(Long id) {
		return dao.find(JobLog.class, id);
	}

	@Override
	@Transactional(readOnly = false)
	public int save(JobLog jobLog) {
		dao.persist(jobLog);
		return 1;
	}

	@Override
	@Transactional(readOnly = false)
	public int updateTriggerInfo(JobLog jobLog) {
		if (jobLog.getTriggerMsg()!=null && jobLog.getTriggerMsg().length()>2000) {
			jobLog.setTriggerMsg(jobLog.getTriggerMsg().substring(0, 2000));
		}
		dao.merge(jobLog);
		return 1;
	}

	@Override
	@Transactional(readOnly = false)
	public int updateHandleInfo(JobLog jobLog) {
		if (jobLog.getHandleMsg() != null && jobLog.getHandleMsg().length() > 2000) {
			jobLog.setHandleMsg(jobLog.getHandleMsg().substring(0, 2000));
		}
		dao.merge(jobLog);
		return 1;
	}

	@Override
	@Transactional(readOnly = false)
	public int delete(Long jobId) {
		dao.remove(dao.getReference(JobLog.class, jobId));
		return 1;
	}

	@Override
	public int triggerCountByHandleCode(int handleCode) {
		return ((Long) dao.createNamedQuery(JobLog.COUNT_BY_HANDLE_CODE).setParameter("handleCode", String.valueOf(handleCode))
			.getSingleResult()).intValue();
	}

	@Override
	public Map<String, Object> triggerCountByDay(Date from, Date to, String handleCode) {
		Map<String, Object> params = new HashMap<String, Object>();
		Query query = dao.createNamedQuery(JobLog.COUNT_BY_HANDLE_CODE_TIME).setParameter("from", from).setParameter("to", to);
		if (handleCode != null) {
			query.setParameter("handleCode", handleCode);
		} else {
			query.setParameter("handleCode", "%");
		}
		@SuppressWarnings("unchecked")
		List<Object[]> rst = query.getResultList();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		for (Object[] objs : rst) {
			params.put(sdf.format(objs[0]), objs[1]);
		}
		return params;
	}

}
